<?php
/**
 * Created by PhpStorm.
 * User: 671643387
 * Date: 2016/9/8
 * Time: 17:04
 */

if(!defined('IN_DISCUZ')) {
    exit('Access Denied');
}

function logMangos($log) {
    require DISCUZ_ROOT . './config/config_global.php';
    file_put_contents($_config['mangos']['logfile'], $log.PHP_EOL, FILE_APPEND);
}

function createMangosUser($username, $password, $email) {
    require DISCUZ_ROOT . './config/config_global.php';

    $db_host = $_config['mangos']['realmd']['dbhost'];
    $db_port = $_config['mangos']['realmd']['dbport'];
    $db_user = $_config['mangos']['realmd']['dbuser'];
    $db_pw = $_config['mangos']['realmd']['dbpw'];
    $db_charset = $_config['mangos']['realmd']['dbcharset'];
    $db_name = $_config['mangos']['realmd']['dbname'];

    // | id              | int(11) unsigned    | NO   | PRI | NULL                | auto_increment |
    // | username        | varchar(32)         | NO   | UNI |                     |                |
    // | sha_pass_hash   | varchar(40)         | NO   |     |                     |                |
    // | gmlevel         | tinyint(3) unsigned | NO   | MUL | 0                   |                |
    // | sessionkey      | longtext            | YES  |     | NULL                |                |
    // | v               | longtext            | YES  |     | NULL                |                |
    // | s               | longtext            | YES  |     | NULL                |                |
    // | email           | text                | YES  |     | NULL                |                |
    // | joindate        | timestamp           | NO   |     | CURRENT_TIMESTAMP   |                |
    // | last_ip         | varchar(30)         | NO   |     | 0.0.0.0             |                |
    // | failed_logins   | int(11) unsigned    | NO   |     | 0                   |                |
    // | locked          | tinyint(3) unsigned | NO   |     | 0                   |                |
    // | last_login      | timestamp           | NO   |     | 0000-00-00 00:00:00 |                |
    // | active_realm_id | int(11) unsigned    | NO   |     | 0                   |                |
    // | expansion       | tinyint(3) unsigned | NO   |     | 0                   |                |
    // | mutetime        | bigint(40) unsigned | NO   |     | 0                   |                |
    // | locale          | tinyint(3) unsigned | NO   |     | 0                   |                |

    $sql = sprintf(
        "INSERT INTO account VALUE (0,'%s','%s',0,'','0','0','%s',CURRENT_TIMESTAMP,'127.0.0.1',0,0,'0000-00-00 00:00:00',0,0,0,0);",
        strtoupper($username), sha1(strtoupper($username . ':' . $password)), $email
    );

    $conn = @mysqli_connect($db_host, $db_user, $db_pw);
    if (!$conn) {
        logMangos(mysqli_connect_error());
        return;
    }
    mysqli_query($conn, "set character set '$db_charset'");
    mysqli_select_db($conn, $db_name);

    if (!mysqli_query($conn, $sql)) {
        logMangos('CREATE NEW MANGOS USER FAILED, ' . mysqli_connect_error());
        mysqli_close($conn);
        return false;
    } else {
        logMangos('CREATE NEW MANGOS USER OK: ' . $sql);
        mysqli_close($conn);
        return true;
    }
}

function json_encode_ex($value)
{
    if (version_compare(PHP_VERSION,'5.4.0','<')) {
        $str = json_encode($value);
        $str = preg_replace_callback(
            "#\\\u([0-9a-f]{4})#i",
            function($matchs)
            {
                return iconv('UCS-2BE', 'UTF-8', pack('H4', $matchs[1]));
            },
            $str
        );
        return $str;
    }
    else {
        return json_encode($value, JSON_UNESCAPED_UNICODE);
    }
}

/**
 * 格式化邮件字符串
 * @param $receiver     收件人
 * @param $subject      标题
 * @param $body         内容
 * @param $money        金币
 * @param $item_id      道具编号
 * @param $item_count   道具数量
 * @return string
 */
function format_mail($receiver, $subject, $body, $money, $item_id, $item_count) {
    $mailData = array(
        'receiver'      => $receiver,
        'subject'       => $subject,
        'body'          => $body,
        'money'         => $money,
    );
    if ($item_id != 0) {
        $mailData['items'] = array(
            array( 'id' => $item_id, 'count' => $item_count )
        );
    }
    return json_encode_ex($mailData);
}

function queryUid($sid, $name) {
    // 取角色数据库配置
    require DISCUZ_ROOT . './config/config_global.php';
    $db_host = $_config['mangos']['chara']['dbhost'];
    $db_port = $_config['mangos']['chara']['dbport'];
    $db_user = $_config['mangos']['chara']['dbuser'];
    $db_pw = $_config['mangos']['chara']['dbpw'];
    $db_charset = $_config['mangos']['chara']['dbcharset'];
    $db_pre = $_config['mangos']['chara']['dbpre'];

    // 查询角色编号
    $conn = @mysqli_connect($db_host, $db_user, $db_pw);
    if (!$conn) {
        logMangos(mysqli_connect_error());
        return;
    }
    mysqli_query($conn, "set character set '$db_charset'");
    mysqli_select_db($conn, $db_pre . $sid);

    $res = mysqli_query($conn, sprintf("SELECT guid FROM characters WHERE name='%s';", $name));
    if ($res) {
        if (mysqli_num_rows($res)) {
            $row = mysqli_fetch_array($res);
            $guid = intval($row['guid']);
            mysqli_free_result($res);
            mysqli_close($conn);
            return $guid;
        }
    }
    mysqli_close($conn);
    return false;
}

function sendMangosMail($username, $sid, $charaname, $score) {
    // 取游戏数据库配置
    require DISCUZ_ROOT . './config/config_global.php';
    $db_host = $_config['mangos']['mangos']['dbhost'];
    $db_port = $_config['mangos']['mangos']['dbport'];
    $db_user = $_config['mangos']['mangos']['dbuser'];
    $db_pw = $_config['mangos']['mangos']['dbpw'];
    $db_charset = $_config['mangos']['mangos']['dbcharset'];
    $db_pre = $_config['mangos']['mangos']['dbpre'];

    // 计算金币数量
    $gold = intval($score / intval($_config['mangos']['S2G']));

    // 回去角色编号
    $charaGuid = queryUid($sid, $charaname);
    if ($charaGuid == false) {
        logMangos("QUERY UID FAILED, ACCOUNT: " . $username . "CHARANAME: " . $charaname . " SID: " . $sid . " 积分: " . $score);
        return false;
    }

    // 构造邮件内容
    $mailStr = format_mail($charaGuid, '[积分兑换金币]', '请查收您兑换的['.$gold.']金币', $gold * 10000, 0, 0);

    // 发送邮件
    $conn = @mysqli_connect($db_host, $db_user, $db_pw);
    if (!$conn) {
        logMangos(mysqli_connect_error());
        return;
    }
    mysqli_query($conn, "set character set '$db_charset'");
    mysqli_select_db($conn, $db_pre . $sid);

    $sql = "INSERT INTO gm_cmds values (0, 1, '$mailStr', 0, CURRENT_TIMESTAMP);";
    $res = mysqli_query($conn, $sql);
    if (!$res) {
        logMangos("SEND MAIL FAILED: " . $sql);
        mysqli_close($conn);
        return true;
    }
    logMangos("SEND MAIL OK: ". $sql);
    mysqli_close($conn);
    return false;
}